package cn.lblbc.appassit.fragment

import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import cn.lblbc.appassit.adapter.AppListAdapter
import cn.lblbc.appassit.databinding.FragmentAppListBinding
import cn.lblbc.appassit.model.AppInfo

private const val TAG = "AppListFragmentPerf"

class AppListFragment : Fragment() {
    
    private var _binding: FragmentAppListBinding? = null
    private val binding get() = _binding!!
    
    private lateinit var appListAdapter: AppListAdapter
    private var allApps = listOf<AppInfo>()
    private var filteredApps = listOf<AppInfo>()
    private var currentSearchQuery = ""
    private var onAppClickListener: ((AppInfo) -> Unit)? = null
    private var onRefreshListener: (() -> Unit)? = null
    private var onSelectionChangedListener: (() -> Unit)? = null
    private var onExportClickListener: ((AppInfo) -> Unit)? = null
    private var onOpenClickListener: ((AppInfo) -> Unit)? = null
    
    companion object {
        fun newInstance(): AppListFragment {
            return AppListFragment()
        }
    }
    
    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        _binding = FragmentAppListBinding.inflate(inflater, container, false)
        return binding.root
    }
    
    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        setupRecyclerView()
        setupSwipeRefresh()
    }
    
    private fun setupRecyclerView() {
        val setupStart = System.currentTimeMillis()
        
        appListAdapter = AppListAdapter(emptyList(), 
            { appInfo ->
                onAppClickListener?.invoke(appInfo)
            },
            { appInfo ->
                onExportClickListener?.invoke(appInfo)
            },
            { appInfo ->
                onOpenClickListener?.invoke(appInfo)
            }
        )
        
        binding.rvAppList.apply {
            layoutManager = LinearLayoutManager(requireContext())
            adapter = appListAdapter
            
            // 性能优化：设置 RecyclerView 的回收池大小
            setRecycledViewPool(RecyclerView.RecycledViewPool())
            
            // 性能优化：设置预取大小，根据设备屏幕大小调整
            val prefetchSize = 2
            if (layoutManager is LinearLayoutManager) {
                (layoutManager as LinearLayoutManager).initialPrefetchItemCount = prefetchSize
            }
            
            // 性能优化：禁用嵌套滚动条（如果不需要）
            isNestedScrollingEnabled = false
            
            // 性能优化：设置自定义回收视图缓存大小
            // 增加缓存以减少视图创建和绑定的开销
            setItemViewCacheSize(20)
        }
        
        // 监听选择状态变化
        appListAdapter.setOnSelectionChangedListener {
            onSelectionChangedListener?.invoke()
        }
        
        Log.d(TAG, "RecyclerView设置完成，耗时${System.currentTimeMillis() - setupStart}ms")
    }
    
    private fun setupSwipeRefresh() {
        binding.swipeRefresh.setOnRefreshListener {
            onRefreshListener?.invoke()
        }
    }
    
    /**
     * 更新应用列表，优化性能版本
     * - 使用AppScanner已经排序好的列表
     * - 移除详细日志输出以提高性能
     */
    fun updateAppList(newAppList: List<AppInfo>) {
        val updateStart = System.currentTimeMillis()
        
        // 确保在主线程上执行UI更新
        if (Looper.myLooper() != Looper.getMainLooper()) {
            Log.w(TAG, "updateAppList: 在非主线程上调用，切换到主线程")
            Handler(Looper.getMainLooper()).post {
                internalUpdateAppList(newAppList)
            }
            return
        }
        
        internalUpdateAppList(newAppList)
        
        Log.d(TAG, "更新应用列表完成，耗时${System.currentTimeMillis() - updateStart}ms")
    }
    
    private fun internalUpdateAppList(newAppList: List<AppInfo>) {
        // 不再对列表进行二次拼音排序，使用AppScanner已经排序好的列表
        // 这显著减少了计算开销
        allApps = newAppList
        
        Log.d(TAG, "更新应用列表: ${allApps.size}个应用")
        
        // 应用搜索过滤器
        val filterStart = System.currentTimeMillis()
        applySearchFilter()
        Log.d(TAG, "应用搜索过滤耗时${System.currentTimeMillis() - filterStart}ms")
        
        // 隐藏刷新指示器
        binding.swipeRefresh.isRefreshing = false
        
        // 优化：在列表更新后，如果列表为空，显示空状态提示
        updateEmptyState()
    }
    
    fun searchApps(query: String) {
        currentSearchQuery = query
        applySearchFilter()
    }
    
    private fun applySearchFilter() {
        filteredApps = if (currentSearchQuery.isBlank()) {
            allApps
        } else {
            allApps.filter { appInfo ->
                appInfo.appName.contains(currentSearchQuery, ignoreCase = true) ||
                appInfo.packageName.contains(currentSearchQuery, ignoreCase = true)
            }
        }
        
        appListAdapter.updateAppList(filteredApps)
        updateEmptyState()
    }
    
    private fun updateEmptyState() {
        val isEmpty = filteredApps.isEmpty()
        binding.llEmptyState.visibility = if (isEmpty && currentSearchQuery.isNotBlank()) {
            View.VISIBLE
        } else {
            View.GONE
        }
        
        if (isEmpty && currentSearchQuery.isNotBlank()) {
            binding.tvEmptyMessage.text = "未找到包含\"$currentSearchQuery\"的应用"
        }
    }
    
    fun setOnAppClickListener(listener: (AppInfo) -> Unit) {
        onAppClickListener = listener
    }
    
    fun setOnRefreshListener(listener: () -> Unit) {
        onRefreshListener = listener
    }
    
    fun setOnSelectionChangedListener(listener: () -> Unit) {
        onSelectionChangedListener = listener
    }
    
    fun setOnExportClickListener(listener: (AppInfo) -> Unit) {
        onExportClickListener = listener
    }
    
    fun setOnOpenClickListener(listener: (AppInfo) -> Unit) {
        onOpenClickListener = listener
    }
    
    fun getSelectedApps(): List<AppInfo> {
        return appListAdapter.getSelectedApps()
    }
    
    fun getSelectedCount(): Int {
        return appListAdapter.getSelectedCount()
    }
    
    fun selectAll() {
        appListAdapter.selectAll()
    }
    
    fun clearSelection() {
        appListAdapter.clearSelection()
    }
    
    fun setSelectionMode(enabled: Boolean) {
        appListAdapter.setSelectionMode(enabled)
    }
    
    fun getAppCount(): Int {
        return filteredApps.size
    }
    
    fun getTotalAppCount(): Int {
        return allApps.size
    }
    
    override fun onDestroyView() {
        super.onDestroyView()
        _binding = null
    }
}